///**************************///
///  VARIABLES Y CONSTANTES  ///
///**************************///
//Variables generales
var cMain = true;				//Parametro que establece la pagina como la principal
var cRefreshmenu; 			 	//Pagina que se tiene que refrescar
var cActivepage;				//Pagina activa
var cMousex, cMousey; 			//Coordenadas del raton
var cIndex = new Array();		//Paginas cargadas
var link = new Array();			//Links cargados
var toggle = new Array();		//Toggles cargados
var vtoggles = new Array();		//Estados de los toggles (Doble array: Nombre toggle y numero de elemento)
var opt = new Array();			//Estados de los links
var cConfirm;                   //Estado de un Cuadro de dialogo
var cDestiny=null;
var cDesactiveMouseMove=false;
//Configuracion e idiomas
var cConfig= new Array();		//Array que guarda las variables que se guardan en el fichero de configuracion
var cLangs= new Array();        //Strings de los idiomas disponibles
var cAbrv= new Array();			//Strings abreviaturas de los idiomas disponibles
var cDirectoryLang = "lang";    //Directorio donde se encuentran los ficheros de idioma disponibles
var cFileLang = "lang";     	//Nombre del fichero que guarda los idiomas disponibles
var cGeneral = new Array();		//Strings basicos que se cargan por defecto cuando escogemos un idioma
var cLanguage;					//Idioma activo

//Varibles precarga
var cItemcount=0;				//Numero de elementos que se cargaran
var cLoadcount=0;				//Elementos de elementos que han finalizado la carga

//Constantes
const cINTERNAL=0;				//Determina que la pagina es interna (Funcion cGO)
const cEXTERNAL=1;				//Determina que la pagina es externa (Funcion cGO)

//Inicio
$(document).ready(function(){
	//localStorage.removeItem("cConfig");
	cConfig = cConfigLoad();
	cConfigLang();
	cConfigUser();
	cStart(cFilename);
});
///*****************///
///  CONFIGURACION  ///
///*****************///
//*********************************************************************************************************
//  cConfigLoad: Devuelve el array con la configuracion predeterminada.
//  Si nunca hemos usado la aplicacion, la configuracion la coge del fichero de configuracion, si ya hemos
//  entrado previamente, la coge del localStorage
//*********************************************************************************************************
function cConfigLoad() {
	if (localStorage.getItem("cConfig")==null) 
		{ cConfig = cStrings("config", "config", "config");
		} else { cConfig = JSON.parse(localStorage.getItem("cConfig")); }
	return cConfig;
}
//*************************************************************
//  cConfigLang: Carga y establece la configuracion del idioma.
//*************************************************************
function cConfigLang() {
	cLanguage = cConfig[0];
	cGeneral = cStrings(cDirectoryLang, cLanguage, "general");
	cLangs = cStrings(cDirectoryLang, cFileLang, "languages");
	cAbrv = cStrings(cDirectoryLang, cFileLang, "abrv");
}
//***************************************
//  cSaveConfig: Guarda la configuracion
//***************************************
function cSaveConfig() {
	localStorage.setItem('cConfig', JSON.stringify(cConfig));
}
//*******************************
//  cStart: Inicia la aplicacion
//*******************************
function cStart(cFilename) {
	if (cConfig[1]==2) {cTRANSITION="fade";} else {cTRANSITION="none";}
    $.mobile.defaultPageTransition = cTRANSITION;
    $.mobile.useFastClick  = false;
    document.title  = cGeneral[0];	
    window.location= cFilename + '#' + cPAGE_PRELOAD;
    cAddPage(cIndex, cPAGE_PRELOAD, cWIDTH_DEFAULT, cHEIGHT_DEFAULT, cMain);
}
///*********************///
/// GESTION DE PAGINAS  ///
///*********************///
//************************************
//  cAddPage: Añade una nueva pagina  
//  ccAddPage (cIndex, "name_page", width, height);  
//************************************
function cAddPage (cIndex, page, wh, ht, cMain) {
	//Variables
	var id = cIndex.length;
	var width;
	var height;
	var cOldLanguage;
	cIndex[id] = page;
	
	//Creamos la pagina si no existe
	if (document.getElementById(page)==null) {cCreatePage(page, wh, ht);}
	
	//Creamos el canvas y el contexto de la pagina
	var theCanvas = document.getElementById(page + "_canvas");	
	var ctx = theCanvas.getContext("2d");
	
	//Le asignamos el tamaño del canvas
	if (wh==null || !wh || wh==undefined) {width = theCanvas.width;} else {width=wh;}  
	if (ht==null || !ht || wh==undefined) {height = theCanvas.height;} else {height=ht;}  

	//PreLoader (Solo para la pagina definida como cPAGE_PRELOAD)
	if (cMain==true) {
		cPreLoader(ctx,width,height);
		cLibraryLoad();	
	} 
	
	//Carga los textos de pagina en el idioma adecuado
	var strings = new Array();
	var cOldLanguage;
	var cActiveGo=false;
	strings =  cStrings (cDirectoryLang, cLanguage, page);
	
	//Listeners 
	theCanvas.addEventListener("click", onMouseClick, false);
	theCanvas.addEventListener("mousemove", onMouseMove, false);
	theCanvas.addEventListener("touchstart", onTouchStart, false);
	theCanvas.addEventListener("touchend", onTouchEnd, false);
	
	//Ciclo de vida de la pagina
	var load = function() {
   		this.run = function() {
   			//Carga los strings de pagina en caso que hayamos cambiado el idioma
   			if (cOldLanguage != cLanguage) { cOldLanguage = cLanguage; strings = new Array(); strings =  cStrings (cDirectoryLang, cLanguage, page); }
   	   		//Cargamos la primera pagina cuando termina de cargar las imagenes (Solo en preloader)
   	   		if (cMain && cItemcount==cLoadcount) { cMain=false; cLoaderPage(ctx, id, width, height, strings);} 
   			// Cuando es necesario recarga la pagina
   			if (page == cRefreshmenu && page!=cPAGE_PRELOAD) { cRefreshmenu=""; cLoaderPage(ctx,id, width, height, strings); }
   			// Cuando la pagina esta activa
			if (page == cActivepage && page!=cPAGE_PRELOAD) {cPressLink(ctx, link, cMousex, cMousey);}
			//Ir a otra pagina
			if (cActiveGo && cDestiny!=null) {if (cDesactiveMouseMove==true) {cMousex=0;cMousey=0;} window.location=cDestiny; cActiveGo= false; cDestiny=null;}
			if (cDestiny!=null) { strings = new Array(); strings =  cStrings (cDirectoryLang, cLanguage, page);cActiveGo=true;}
   		};
		var intervalId = setInterval(this.run, 1000 / cFPS);
	};
	load();
}
///****************************************************
/// cCreatePage: Crea una pagina
/// cCreatePage("name_page", width,height);
///****************************************************
function cCreatePage(page, width,height) {
	if (!width || width==null) {width=cWIDTH_DEFAULT;}
    if (!height || height==null) {height=cHEIGHT_DEFAULT;}
	$('BODY').prepend('<div data-role="page" class="full" id="' + page + '" data-position="fixed"><div class="divcanvas"><canvas class="canv" id="' + page + '_canvas" width="' + width + '" height="' + height + '">Tu navegador no soporta HTML5 Canvas</canvas></div></div>');
}
///****************************************************
/// cLoaderPage (Carga la pantalla adecuada)
/// cLoaderPage(ctx, index, width, height, strings);
///****************************************************
function cLoaderPage(ctx, index, width, height, strings) {
	var menulist = "loader_" + cIndex[index];
	eval(menulist) (ctx, cIndex[index], width, height, strings);
}
//****************************************************************************************************************
//  cGo: Ir a una pagina (El segundo parametro es opcional y por defecto es cInternal)
//  Ej: cGo("pagemenu", cInternal);  cGo("http://google.com", cExternal); 
//****************************************************************************************************************
function cGo (page, destiny) {
	if (!destiny || destiny==null) { var destiny = 0;}
	if (destiny>1) {destiny=1;}	

	if (destiny==0) {
		cActivepage = page;
		cRefreshmenu = page;
		cDestiny = 'index.html#' + page;
	} else {
		window.open(page, '_blank');
	}
}
///********************************************************************************************************************
/// FUNCIONES GRAFICAS
///********************************************************************************************************************
//*********************************
//  cLoadImg: Precargar una imagen
//	cLoadImg(image);
//*********************************
function cLoadImg(image) {
	cItemcount++;
	var name = new Image();
	name.src = image;
	name.onload = function() {cLoadcount++;}	
	return name;
}
//************************************************************************************************
//  Limpia area de la pantalla con un color, si le aplicamos el 'reset' borrara efectos de eventos
//  cClear(ctx, width, height, "#CCC", true);
//************************************************************************************************
function cClear(ctx, x, y , width, height, color, reset) {
	ctx.beginPath();
	cShadow(ctx, [0,0,0,null]);
	if (reset) { 
				link = new Array();
				toggle = new Array();
		}
	
	ctx.setTransform(1,0,0,1,0,0);
	if (!color) 
		{
			ctx.clearRect(x,y,width,height);
		} else 	{
			ctx.fillStyle = color;
			ctx.fillRect(x, y, width, height);
		}
	ctx.closePath();	
}
//*****************************************************************************************
//  Colocar imagen en pantalla (Permite modificar el tamaño y recortar parte de la imagen)
//  cImg(ctx, _logo, 50, 50, 100, null, [32,32],[0,0,32,32]);
//*****************************************************************************************
function cImg(ctx, visible, img, x, y, alpha, shadow, size, crop) {
	//Comprovaciones
	ctx.beginPath();
	if (visible==null || typeof visible!="boolean") { var visible = true;}
	if (visible==true) { 	
		if (!size || size==null || typeof size!="object") { var size = new Array(2); size[0] = img.width; size[1] = img.height;}
		if (!shadow || shadow==null || typeof shadow!="object") {var shadow = new Array(4); shadow[0]=0;shadow[1]=0;shadow[2]=0;shadow[3]=0;} 
		if (!alpha || alpha==null || typeof alpha!="number") {var alpha =100;}
	
		var res = new Array(2);
		var size_ok= new Array(2);
		res[0]= img.width;
		res[1]= img.height;
		
		size_ok = cParamSpecial(size, res, img);
	
		//Recortar imagen
		if (!crop || crop==null || typeof crop!="object") { var crop = new Array(4); crop[0] = 0; crop[1] = 0; crop[2] = img.width; crop[3] = img.height;}
		if (crop[2]>img.width) {crop[2]=img.width;}
		if (crop[3]>img.height) {crop[3]=img.height;}
	
		cShadow(ctx, shadow);
		ctx.setTransform(1,0,0,1,0,0);
		ctx.translate(-.5*size_ok[0],-.5*size_ok[1]);	
		ctx.globalAlpha = alpha/100;
		ctx.drawImage(img, crop[0], crop[1], crop[2], crop[3], x, y, size_ok[0], size_ok[1]);
	}
	ctx.closePath();
}
//******************************************************************************************************************************
//  Coloca texto en la pantalla (Fill, Stroke o los dos), se le puede poner una area para efectos de degradado y cuadrar botones
//	cText(ctx, text, x, y, type, [color1,color2], font, alpha, [shadow_x,shadow_y,shadow_blur,shadow_color], [area_w, area_h]);
//******************************************************************************************************************************
function cText(ctx, visible, text, x, y, type, color, font, alpha, shadow, area) {
	//Comprovaciones
	ctx.beginPath();
	if (visible==null || typeof visible!="boolean") { var visible = true;}
	if (visible==true) { 
		
		if (!area || area==null || typeof area!="object") { var area = new Array(2); area[0]= 0; area[1]=0;}
		if (!shadow || shadow==null || typeof shadow!="object") {var shadow = new Array(4); shadow[0]=0;shadow[1]=0;shadow[2]=0;shadow[3]=0;} 
		if (!alpha || alpha==null || typeof alpha!="number") {var alpha =100;}
		if (!font || font==null) {var font =18;}
		if (typeof font=="number") {ctx.font = font + "px fantasy";} else {ctx.font = font;}
		if (!color || color==null || typeof color!="object") { var color = new Array(2); color[0]= "#FFF"; color[1]="#000";}
		if (!type || type==null || typeof type!="string") { var type = "f";}
		
		var pen =0;
		var typestyle=0;
		var value = new Array(2); 
		var size = parseInt(font);
	
		cShadow(ctx, shadow);
		ctx.setTransform(1,0,0,1,0,0);	
		ctx.translate(-.5*area[0],-.5*area[1]);
		ctx.globalAlpha = alpha/100;
	
		value = cTypeStyle(type);
		typestyle = value[0];
		pen = value[1];
		
		if (typestyle>0) {ctx.lineWidth = pen;}
		var metrics = ctx.measureText(text);
		var textwidth= metrics.width;
	
		cApplyColor(ctx, color, x,y, area);
	
		//Fill
		if (typestyle ==0 || typestyle==2) {
			ctx.fillStyle = color[0]; 
			ctx.fillText (text, x+.5*area[0]- .5*textwidth,y + .5*area[1] + .33*size);	
		}
		//Stroke
		if (typestyle ==1 || typestyle==2) {
			ctx.strokeStyle =color[1]; 
			ctx.strokeText (text, x+.5*area[0]- .5*textwidth,y + .5*area[1] + .33*size);	
		}
	}
	ctx.closePath();
	ctx.globalAlpha = 100;
}
//*******************************************************************************
//  cRect: Dibuja Rectangulo rellenos, contorno o ambos, ambite redondeo de esquinas 
//  cRect(ctx,x,y,width,height,"fs4",["sblue","s#CCC"],8,100,[2,2,2,"#000"]);
//*******************************************************************************
function cRect(ctx, visible, x, y , width, height, type, color, rounded, alpha, shadow) {
	//Comprovaciones
	ctx.beginPath();
	if (visible==null || typeof visible!="boolean") { var visible = true;}
	if (visible==true) { 	
		
		if (!shadow || shadow==null || typeof shadow!="object") {var shadow = new Array(4); shadow[0]=0;shadow[1]=0;shadow[2]=0;shadow[3]=0;} 
		if (!alpha || alpha==null || typeof alpha!="number") {var alpha =100;}
		if (!color || color==null || typeof color!="object") { var color = new Array(2); color[0]= "#FFF"; color[1]="#000";}
		if (!type || type==null || typeof type!="string") { var type = "f";}
	
		var pen =0;
		var typestyle=0;
		var value = new Array(2); 
		var area = new Array(2);
		area[0]=width;
		area[1]=height;
		
		cShadow(ctx, shadow);
		ctx.setTransform(1,0,0,1,0,0);	
		ctx.translate(-.5*area[0],-.5*area[1]);
		ctx.globalAlpha = alpha/100;	
		
		value = cTypeStyle(type);
		typestyle = value[0];
		pen = value[1];
	
		if (typestyle>0) {ctx.lineWidth = pen;}
		
		cApplyColor(ctx, color, x,y, area);
	
		//Fill
		if (typestyle ==0 || typestyle==2) {
			ctx.fillStyle = color[0];
			cRounded(ctx,0, rounded, x, y, width,height);
		}
		//Stroke
		if (typestyle ==1 || typestyle==2) {
			ctx.strokeStyle =color[1]; 
			cRounded(ctx,1, rounded, x, y, width,height);
		}
		
	}
	ctx.closePath();
}
//**********************************************************************************************
//  Rectangulos basicos (Sin estilo)
//  cRounded(ctx, style, rounded,x,y,rWidth,rHeight); // style=0 (Relleno) | style=1 (Contorno)
//**********************************************************************************************
function cRounded(ctx, style, rounded,x,y,rWidth,rHeight) {
	if (cConfig[1]<2) {rounded=0;}
	if (!rounded || rounded==0) {
		if (style==0) {ctx.fillRect(x,y,rWidth,rHeight);} else {ctx.strokeRect(x,y,rWidth,rHeight);}
	} else {
		ctx.moveTo(x + rounded, y);
		ctx.lineTo(x + rWidth - rounded, y);
		ctx.quadraticCurveTo(x + rWidth, y, x + rWidth, y + rounded);
		ctx.lineTo(x + rWidth, y + rHeight - rounded);
		ctx.quadraticCurveTo(x + rWidth, y + rHeight, x + rWidth - rounded, y + rHeight);
		ctx.lineTo(x + rounded, y + rHeight);
		ctx.quadraticCurveTo(x, y + rHeight, x, y + rHeight - rounded);
		ctx.lineTo(x, y + rounded);
		ctx.quadraticCurveTo(x, y, x + rounded, y);
		if (style==0) {ctx.fill();} else {ctx.stroke();}
	}
}

//********************
//  Sombras
//********************
function cShadow(ctx, shadow) {
	if (cConfig[1]==0) {shadow[0]=0;shadow[1]=0;shadow[2]=0;shadow[3]=0;}	
	ctx.shadowOffsetX = shadow[0];
	ctx.shadowOffsetY = shadow[1];
	ctx.shadowBlur    = shadow[2];
	ctx.shadowColor =   shadow[3];
	

}

//*******************************************************************************
//  cTypeStyle: Identifica si es fill, stroke o ambos y el grosor del stroke
//  Devuelve un array con el tipo y el grosor del stroke
//*******************************************************************************
function cTypeStyle(type) {
	var value = new Array(2); 
	switch(type.length) {
	 	case 1: if (type.substr(0,1).toLowerCase()=="s") {value[0]= 1; value[1]=1;} else {value[0]= 0;} break;
	 	case 2: value[0]=-1;
	 			if (type.substr(0,1).toLowerCase()=="s" && (!isNaN(parseFloat(type.substr(1))) && isFinite(type.substr(1)))) {value[0]= 1; value[1]=type.substr(1);}
	 			if (type.toLowerCase()=="fs") {value[0]= 2; value[1]=1;}	
				if (value[0]==-1) {value[0]=0;}											 
	 			break;
		case 3: 
		case 4:
				value[0]=-1;
				if (type.substr(0,1).toLowerCase()=="s" && (!isNaN(parseFloat(type.substr(1))) && isFinite(type.substr(1)))) {value[0]= 1; value[1]=type.substr(1);}															
				if (type.substr(0,2).toLowerCase()=="fs" && (!isNaN(parseFloat(type.substr(2))) && isFinite(type.substr(2)))) {value[0]= 2; value[1]=type.substr(2);}	
				if (value[0]==-1) {value[0]=0;}	
				break;	
	 	default: value[0] = 0; break;
	}
	return value;
}
//*******************************************************************************************
//  cApplyColor: Genera el tipo de style para Fill y Stroke: solid, pattern, radial o linear
//*******************************************************************************************
function cApplyColor(ctx, color,x,y, area) {
	for (var j=0; j<color.length;j++) {
		if (color[j]==null) {color[j]= "#000";} else { 
			typecolor = color[j].substr(0,1).toLowerCase();
			colorpure = color[j].substr(1);
			if (typecolor.toLowerCase()=="s") {color[j]= colorpure;}
			if (typecolor.toLowerCase()=="i") {color[j] = ctx.createPattern(eval(colorpure), "repeat");}
			if (typecolor.toLowerCase()=="l" || typecolor.toLowerCase()=="r" ) {
				var p = new Array(4);
				var typegradient = colorpure.substr(0,1);	
				var gradient = eval(colorpure.substr(1));	
				
				//alert(p[0] + " - " + p[1] + " - " + p[2] + " - " + p[3] + " - ");  //ARREGLAR EL FOCO DEL GRADIENT !!!! 
				if (typecolor.toLowerCase()=="l") { tipo = ctx.createLinearGradient(p[0], p[1], p[2], p[3]); }
				if (typecolor.toLowerCase()=="r") {tipo = ctx.createRadialGradient(p[0], p[1], 1 , p[0], p[1], area[0]); }
				for (var i=0; i<gradient.length; i++) {
					tipo.addColorStop(gradient[i][1], gradient[i][0]);
					}		
				color[j] = tipo;	
			}
		}
	}	
}
//*******************************************************************************************
//  cParamSpecial: Calculos para parametros especiales ( '+' '-' '*' '/')
//*******************************************************************************************
function cParamSpecial(size, res, img) {
	for (var i=0; i<res.length; i++) {
		if (typeof size[i]=="string") { 
			var opera= size[i].substr(0,1);
			var modi=0;
			if (opera=="+") {modi=1; size[i] = res[i] + parseInt(size[i].substr(1)) ; }
			if (opera=="-") {modi=2; size[i] = res[i] - parseInt(size[i].substr(1)) ; }
			if (opera=="*") {modi=3; size[i] = res[i] * parseInt(size[i].substr(1)) ; }
			if (opera=="/") {modi=4; size[i] = res[i] / parseInt(size[i].substr(1)) ; }
			if (modi==0) { size[i] = size[i].substr(0);}
			if (size[i]<0) {size[i]=0;}
		}
	}
	if (size[0]==null) {size[0]=img.width;}
	if (size[1]==null) {size[1]=img.height;}
	return size;		
}
///********************************************************************************************************************
/// EVENTOS: BOTONES, TOGGLES, etc...
///********************************************************************************************************************
//************************************************
//  Gestiona los eventos de click del raton
//************************************************
function onMouseClick (e){
	cClickLink(link, cMousex, cMousey); 
	cClickToggle(toggle, cMousex, cMousey);
}
//************************************************
//  Gestiona los eventos del movimiento del raton
//************************************************
function onMouseMove (e){
	if (cDesactiveMouseMove==false) {
		cMousex = (e.pageX- this.offsetLeft) / (this.offsetWidth/this.width);
		cMousey = (e.pageY- this.offsetTop) / (this.offsetHeight/this.height);
	}
}
function onTouchStart (e){
	cDesactiveMouseMove=true;
	var first = e.changedTouches[0];
	cMousex = (first.clientX- this.offsetLeft) / (this.offsetWidth/this.width);
	cMousey = (first.clientY- this.offsetTop) / (this.offsetHeight/this.height);
}

function onTouchEnd (e){
	//cMousex = 0;
	//cMousey = 0;
}
//***********************************************************************************************************
//  Crear un boton de link (Botones de menu)
//  cCreateMenu (link, x,y,width,height,imgON,imgOFF,action,data); //action=pagelink data=variable userdata
//***********************************************************************************************************
function cLink (ctx, page, strings, group, area, action, elements) {
	var nx = link.length;
	link[nx] = new Array(11);
	link[nx][0]=area[0]; link[nx][1]=area[1]; link[nx][2]=area[2]; link[nx][3]=area[3]; link[nx][5]=strings; link[nx][6]=group; link[nx][7]=action; link[nx][8]=elements; link[nx][9]=page; link[nx][10]=ctx;
}
//*******************************************************************
//  Comprueba que link hemos pulsado y nos envia al nuevo destino
//  link[i][7] contiene la variable userdata para eventos especiales
//*******************************************************************
function cClickLink (link, cMousex, cMousey) {
	for (var i=0; i<link.length; i++) {
		width = link[i][2]; height = link[i][3];
		strings= link[i][5]; elements = link[i][8]; page = link[i][9];  ctx = link[i][10]; 
		if (cActivepage == link[i][9] && cMousey>link[i][1]- .5*link[i][3] && cMousey<(link[i][1]- .5*link[i][3] + link[i][3]) && cMousex>link[i][0]- .5*link[i][2] && cMousex<(link[i][0]- .5*link[i][2] + link[i][2])) {cRefreshmenu= link[i][9]; eval(link[i][7]);}
	}
}
//********************************************************************************************
//  Activar boton de link (Botones de menu)
//  Comprueba si estamos encima de algun link, y en caso afirmativo cambia la imagen (ON/OFF)
//********************************************************************************************
function cPressLink (ctx, link, cMousex, cMousey) {
	var opt = new Array();
	for (var i=0; i<link.length; i++) {
		strings= link[i][5]; elements = link[i][8]; page = link[i][9];  ctx = link[i][10]; 
		if (cActivepage == link[i][9]) {
			if (cMousey>link[i][1]- .5*link[i][3] && cMousey<(link[i][1]- .5*link[i][3] + link[i][3]) && cMousex>link[i][0]- .5*link[i][2] && cMousex<(link[i][0]- .5*link[i][2] + link[i][2])) 
				{if (opt[0]!=true) {cRefreshmenu = link[i][9];} opt[0] = false; opt[1] = true; eval(elements);} 
				else 
				{if (opt[0]!=false) {cRefreshmenu = link[i][9];} opt[0] = true; opt[1] = false; eval(elements);}
		}
	}
}
//*****************************************************************
//  Crear un interruptor (Checkboxes, buttontoggle, etc...)
//	cCreateToggle (toggle, x,y,width,height,imgON,imgOFF, state);
//*****************************************************************
function cToggle (ctx, page, strings, group, area, action, state) {
	var nx = toggle.length;
	toggle[nx] = new Array(10);
	toggle[nx][0]=area[0]; toggle[nx][1]=area[1]; toggle[nx][2]=area[2]; toggle[nx][3]=area[3]; toggle[nx][5]=strings; toggle[nx][6]=group; toggle[nx][7]=action; toggle[nx][8]=page; toggle[nx][9]=ctx; 

	if (vtoggles[nx]==undefined) 
			{
				vtoggles[nx] = new Array(2); vtoggles[nx][0]= group; vtoggles[nx][1]= state; eval(action);
			} else {
				eval(action);
			} 
}
//***********************************************************************************************
//  Activar interruptor
//  Comprueba si hemos pulsado algun interruptor, y en caso afirmativo cambia el estado (ON/OFF)
//***********************************************************************************************
function cClickToggle (toggle, cMousex,cMousey) {
	for (var i=0; i<toggle.length; i++) {
			action = toggle[i][7]; ctx = toggle[i][9]; 
			if (cActivepage == toggle[i][8] && cMousey>toggle[i][1]- .5*toggle[i][3] && cMousey<(toggle[i][1]- .5*toggle[i][3] + toggle[i][3]) && cMousex>toggle[i][0]- .5*toggle[i][2] && cMousex<(toggle[i][0]- .5*toggle[i][2] + toggle[i][2]))
				{ 
				   
				  vtoggles[i][1]++; eval(action);
			    }
	}
}
//***********************************************************************************************
//  cToggleAction: Devuelve en que elemento del toggle estamos y define unos limites
//  Ej: obj= cToggleAction(vtoggles, "graficos", start , end);
//***********************************************************************************************
function cToggleAction(vtoggles, element, start, end) {
	var obj = -1
	for (var i=0; i<vtoggles.length; i++) {
		if (vtoggles[i].indexOf(element)!=-1) {id = i; obj= vtoggles[i][1];};	
	}	
	if (vtoggles[id][1]>end) {vtoggles[id][1]=start; obj=vtoggles[id][1];}
	if (vtoggles[id][1]<start) {vtoggles[id][1]=end; obj=vtoggles[id][1];}
	return obj;
}
///********************************************************************************************************************
/// MISC
///********************************************************************************************************************
//***********************************************************************************************************
// cStrings: Devuelve los arrays en el idioma definido de un fichero JSON
// Ej: cStrings ("directory", "file", "loads"); (Obtiene los arrays de 'loads' del fichero directory/file.json)
//***********************************************************************************************************
function cStrings (url, file, name) {
	if (!url || url==undefined) {url= "lang";}
	if (!file || file==undefined) {file= "lang";}
	var strings = {};
    $.ajax({
        url: url + '/' + file + '.json',
        async: false,
        dataType: 'json',
        success: function(data) {
					var val = "data." + name;
					strings = eval(val);
        }
    });
	return strings;
}
//****************************************
// Recuperar parametro de un metodo post
// Ej: index.html?x=23 --> x = cParam(x);
//****************************************
function cParam(name) {
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp(regexS);
	var tmpURL = window.location.href;
	var result = regex.exec(tmpURL);
	if (result == null) {
		return "";
	} else {
		return result[1];
	}
}
